<template>
  <div class="edit">
    <div class="top">
      <span class="text">上传头像</span>
    <van-uploader v-model="fileList" multiple :max-count="1" />
    </div>
    <van-field v-model.trim="nickname" class="nickname" label="昵称" placeholder="输入修改后的昵称" />
    <van-field
      v-model.trim="des"
      rows="2"
      autosize
      label="个新签名"
      type="textarea"
      maxlength="50"
      placeholder="请输入个新签名"
      show-word-limit
    />
    <!-- Button 按钮组件 点击保存 -->
    <van-button
      type="primary"
      block
      color="#1989fa"
      @click="handleSave"
    >
      保存修改
    </van-button>
  </div>
</template>

<script>
import Vue from 'vue'
import { Toast } from 'vant'
Vue.use(Toast)
export default {
  name: 'edit',
  created () {
    this.info = this.$store.state.userInfo.filter(user => user.username === this.$store.state.username)[0]
    this.des = this.info.des
    this.nickname = this.info.nickname
    this.fileList.push({
      content: this.info.imgUrl,
    })
  },
  data () {
    return {
      fileList: [],
      nickname: '',
      des: '',
      info: '',
      timeout: '',
    }
  },
  methods: {
    handleSave () {
      if (this.nickname === this.info.nickname && this.des === this.info.des && this.fileList[0]?.content === this.info.imgUrl) {
        Toast.fail('没有数据\n被修改')
        return
      } else if (!this.nickname) {
        this.nickname = this.info.nickname
        Toast.fail('昵称不能为空')
        return
      }
      this.$store.commit('handleEdit', {
        nickname: this.nickname,
        imgUrl: this.fileList[0]?.content,
        des: this.des,
      })
      // 提示编辑成功
      Toast.success({
        message: '编辑成功',
        forbidClick: true,
      })
      // 1 秒之后跳转到明细页面，提升用户体验
      this.timeout = setTimeout(() => {
        this.$router.push({
          name: 'mine',
        })
      }, 1000)
    },
  },
  beforeDestroy () {
    clearTimeout(this.timeout)
  },
}
</script>

<style lang="less" scoped>
.top{
  position: relative;
  height: 100px;
}
button{
  margin-top: 10px;
  text-align: center;
}
.text{
  font-size: 14px;
  position: absolute;
  top: 50%;
  margin-top: -10px;
  left: 18px;
}
/deep/.van-uploader{
  position: absolute;
  margin-top: 10px;
  left: 50%;
  margin-left: -40px;
}
</style>
